home *** CD-ROM | disk | FTP | other *** search
- Path: news.halcyon.com!usenet
- From: normanb@halcyon.com (Norm Bryar)
- Newsgroups: comp.lang.c++
- Subject: Re: String operator+ and memory leakage.
- Date: Fri, 19 Apr 1996 15:16:06 GMT
- Organization: Northwest Nexus Inc.
- Message-ID: <4l8am8$701@news.halcyon.com>
- References: <4l5foo$fen@utopia.hacktic.nl>
- NNTP-Posting-Host: blv-pm3-ip4.halcyon.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- Mike Tavares <MIKET@cdynamics.com> wrote:
-
- >I have an implementation (not mine) of the String class that is leaking
- >memory
- >during the + operator code. The code follows:
-
- >class String
- > {
- > public:
-
- > // Constructors/destructors
- > String();
- > String( char* new_string);
- > String( String& new_string);
-
- > ~String()
- > {
- > delete character_array;
- > }
-
- > String& operator+( String& a_string );
- > String& operator=( String& a_string );
- > operator char* () { return character_array; }
-
- > private:
-
- > char* character_array;
- > int string_length;
- > };
-
- >String&
- >String::operator+( String& a_string )
- > {
- > int total_size = string_length + strlen( a_string ) + 1;
- > char* temp_array = new char[total_size];
- > char* char_array = a_string;
-
- > strcpy( temp_array, character_array );
- > strcat( temp_array, char_array );
-
- > String* new_string = new String( temp_array );
- > delete [] temp_array;
- > return *new_string;
- > }
- > ...
- >My usage is:
-
- >destString = string1 + string2 + string3...;
-
- >The problem is, when new_string is created and returned through a
- >reference, no one ever deletes it.
-
- >If I change new_string to be an automatic variable I get an error from
- >the compiler about trying to pass a reference to a item that is out of
- >scope.
-
- >If I change the method to work in this I mutate one of my addends. There
- >has to be a way of implementing this without memory leakage! HELP!
-
- >TIA
-
- >=MikeT
-
- > ---------------------------------------------------------------------
- >| Mike Tavares | miket@cdynamics.com | |
-
- This doesn't seem like a very well thought-out string class.
- operator+() should return a string, not a string &, I should think.
-
- String String::operator+( const String & aString ) const
- {
- int totalsize = string_length + aString.string_length;
- char * temp = new char[ totalsize ];
- ... etc...
- return String( temp );
- }
-
- The nameless automatic returned will go out-of-scope and clean-up
- automatically. Returning a nameless object instead of a named object
- allows the compiler to potentially optimize the code so you may not
- end up calling a copy-ctor to go from operator+'s stack frame to the
- callee's stack-frame. And, of course, no dangling news!
-
- --Norm
-
-
-